﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Windows.Forms;
using CefSharp.WinForms;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Garbage_Services_Terminator
{
    public partial class Main : UIForm
    {

        internal int ljfwCount = 0,sum = default(int),n1 = 0,n2 = 0;
        internal List<string> servicesArray = new List<string>();
        internal string[] diffArray;

        [DllImport("User32.dll ", EntryPoint = "SetParent")]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("user32.dll ", EntryPoint = "ShowWindow")]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

        public Main()
        {
            //反射关键集
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            //加载Chromium内核
            string url = "https://forms.office.com/Pages/ResponsePage.aspx?id=TVmVBDZlMkKXdiu4emLqnFiH7ZKSoYBHnWA9UQhneWlUQkRUQU1YSzhFUDQxUU9GQk8xRzFSVEoyUi4u";
            ChromiumWebBrowser webview = new ChromiumWebBrowser(url);
            webview.Dock = DockStyle.Fill;

            InitializeComponent();

            this.tabPage4.Controls.Add(webview);
        }

        System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string dllName = args.Name.Contains(",") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
            dllName = dllName.Replace(".", "_");
            if (dllName.EndsWith("_resources")) return null;
            System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
            byte[] bytes = (byte[])rm.GetObject(dllName);
            return System.Reflection.Assembly.Load(bytes);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //webBrowser1.Navigate("https://forms.office.com/Pages/ResponsePage.aspx?id=TVmVBDZlMkKXdiu4emLqnFiH7ZKSoYBHnWA9UQhneWlUQkRUQU1YSzhFUDQxUU9GQk8xRzFSVEoyUi4u");

            Random rd = new Random();

            n1 = rd.Next(0, 100);
            n2 = rd.Next(0, 100);

            sum = n1 * n2;

            label4.Text = $"2.回答问题：{n1} * {n2} = ?";

            Process p = new Process();
            //命令提示符
            p.StartInfo.FileName = "cmd.exe ";
            p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;//加上这句效果更好
            p.Start();
            System.Threading.Thread.Sleep(100);//加上，100如果效果没有就继续加大

            SetParent(p.MainWindowHandle, panel2.Handle); //panel1.Handle为要显示外部程序的容器
            ShowWindow(p.MainWindowHandle, 5);

            //获取个人信息
            if (File.Exists(Application.StartupPath + "\\as.txt"))
            {
                string userInfo = (new StreamReader(Application.StartupPath + "\\as.txt")).ReadToEnd();
                string[] userInfoProcessed = userInfo.Split(';');

                //POST
                string license = MethodBox.Interface.Login.RequestData(userInfoProcessed[0], "http://4ptcifn7j9.258jz.cn/api/login.php", $"username={userInfoProcessed[0]}&password={userInfoProcessed[1]}", new List<string> { "A0" },false);
                string userId = MethodBox.Interface.Login.RequestData(userInfoProcessed[0], "http://4ptcifn7j9.258jz.cn/api/getID.php", $"username={userInfoProcessed[0]}&password={userInfoProcessed[1]}", new List<string> { "A0" },false);

                label6.Text = $"用户ID ： {userId}";
                label7.Text = $"用户名 ： {userInfoProcessed[0]}";
                byte[] md5 = Encrypt.Md5(userInfoProcessed[1]);
                label8.Text = $"秘 钥 ： {md5[(new Random()).Next(1,8)]}{md5[(new Random()).Next(1, 8)]}{md5[(new Random()).Next(1, 10)]} - {md5[(new Random()).Next(10, 14)]}{md5[(new Random()).Next(14, 15)]}{md5[(new Random()).Next(1, 15)]} - {md5[(new Random()).Next(1, 15)]}";
                
                label9.Text = "联系方式 ： 邮箱或电话";
                label10.Text = $"许可证 ： MethodBox {license} License";
                uiButton2.Visible = false;
                uiButton3.Visible = false;
            }

        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            uiListBox1.Items.Clear();
            ljfwCount = 0;
            servicesArray.Clear();

            //获取所有服务

            ServiceController[] allServices = ServiceController.GetServices();
            foreach (var item in allServices)
            {
                //加入服务集
                servicesArray.Add(item.ServiceName);

            }

            int ctTemp = servicesArray.Count;

            //垃圾服务集
            List<string> rubbishServiceArray = new List<string>(GetServicesWeb.GarbageGetter());

            //获取垃圾服务（求交集的补集）
            diffArray = servicesArray.Where(c => rubbishServiceArray.Contains(c)).ToArray();

            ljfwCount = diffArray.Length;

            //回显结果
            uiLabel2.Text = $"扫描完成。我们共找到服务{ctTemp}个，其中垃圾服务{ljfwCount}个。";

            foreach (var servc in diffArray)
            {
                uiListBox1.Items.Add(servc);
            }


            uiRichTextBox1.Text = "";

            foreach (var item in diffArray)
            {
                uiRichTextBox1.Text += $"net stop {item}\n";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel2.Text = "                                             " + DateTime.Now.ToString(); //获取系统时间
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            StreamWriter sw = new StreamWriter(Application.StartupPath + "\\servc.bat");
            sw.Write(uiRichTextBox1.Text);
            MessageBox.Show("已经保存到" + Application.StartupPath + "\\servc.bat" + "！");
            sw.Close();

        }

        public int getbunch(string p, string s)  //给关键字上色
        {
            int cnt = 0; int M = p.Length; int N = s.Length;
            char[] ss = s.ToCharArray(), pp = p.ToCharArray();
            if (M > N) return 0;
            for (int i = 0; i < N - M + 1; i++)
            {
                int j;
                for (j = 0; j < M; j++)
                {
                    if (ss[i + j] != pp[j]) break;
                }
                if (j == p.Length)
                {
                    this.uiRichTextBox1.Select(i, p.Length);
                    this.uiRichTextBox1.SelectionColor = Color.Blue;
                    cnt++;
                }
            }
            return cnt;

        }

        private void uiListBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {

        }

        private void uiRichTextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (uiRichTextBox1.Text.Substring(0,1) == "r")
                {
                    uiRichTextBox1.Text = "";
                    int index = this.uiRichTextBox1.SelectionStart;    //记录修改的位置
                    uiRichTextBox1.Text += "net ";
                    this.uiRichTextBox1.Select(index + 5, 0);     //返回修改的位置
                }
                else
                {
                    int index = this.uiRichTextBox1.SelectionStart;    //记录修改的位置
                    uiRichTextBox1.Text += "net ";
                    this.uiRichTextBox1.Select(index + 5, 0);     //返回修改的位置
                }
            }
        }

        private void uiRichTextBox1_TextChanged(object sender, EventArgs e)
        {
            int index = this.uiRichTextBox1.SelectionStart;    //记录修改的位置
            this.uiRichTextBox1.SelectAll();
            this.uiRichTextBox1.SelectionColor = Color.Black;


            string[] keystr = { "net", "stop","rem","start" };
            for (int i = 0; i < keystr.Length; i++)
                this.getbunch(keystr[i], this.uiRichTextBox1.Text);

            this.uiRichTextBox1.Select(index, 0);     //返回修改的位置
            this.uiRichTextBox1.SelectionColor = Color.Black;

            //生成命令行
            string[] mlh = uiRichTextBox1.Text.Split('\n');
            textBox1.Text = "";

            foreach (var item in mlh)
            {
                if (item != string.Empty)
                {
                    if (textBox1.Text == string.Empty)
                    {
                        textBox1.Text += item;
                    }
                    else
                    {
                        textBox1.Text += $"&{item}";
                    }
                }
            }
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            string strInput = textBox1.Text;
            Process p = new Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = "cmd.exe";
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardInput = true;
            //输出信息
            p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            //启动程序
            p.Start();

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(strInput + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取输出信息
            string strOuput = p.StandardOutput.ReadToEnd();
            //等待程序执行完退出进程
            p.WaitForExit();
            p.Close();

            MessageBox.Show("命令完成。如需获取详细信息，请尝试使用MethodBox BatEditor。","成功",MessageBoxButtons.OK,MessageBoxIcon.Information);

        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            if (textBox2.Text == sum.ToString())
            {
                if (radioButton1.Checked)
                {
                    //加载Chromium内核
                    string url = "https://forms.office.com/Pages/ResponsePage.aspx?id=TVmVBDZlMkKXdiu4emLqnFiH7ZKSoYBHnWA9UQhneWlUOUVHT1RPSjlIUVNIRkNIVlVJUVlMTzdCSi4u";
                    ChromiumWebBrowser webview = new ChromiumWebBrowser(url);
                    webview.Dock = DockStyle.Fill;
                    tabPage7.Controls.Add(webview);
                    uiTabControlMenu1.SelectedIndex = 5;
                }
                else if (radioButton2.Checked || radioButton3.Checked)
                {
                    //加载Chromium内核
                    string url = "https://forms.office.com/r/LHUcwpsRwD";
                    ChromiumWebBrowser webview = new ChromiumWebBrowser(url);
                    webview.Dock = DockStyle.Fill;
                    tabPage7.Controls.Add(webview);
                    uiTabControlMenu1.SelectedIndex = 5;
                }
                else if (radioButton4.Checked)
                {
                    //加载Chromium内核
                    string url = "https://forms.office.com/r/whBLYLZ2BU";
                    ChromiumWebBrowser webview = new ChromiumWebBrowser(url);
                    webview.Dock = DockStyle.Fill;
                    tabPage7.Controls.Add(webview);
                    uiTabControlMenu1.SelectedIndex = 5;
                }
                else
                {
                    MessageBox.Show("请先选中一个选项！","Null",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("问题回答错误!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                Random rd = new Random();
                n1 = rd.Next(0, 100);
                n2 = rd.Next(0, 100);
                sum = n1 * n2;

                label4.Text = $"2.回答问题：{n1} * {n2} = ?";
                textBox2.Text = "";
                textBox2.Focus();
            }
        }

        private void 读取ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //读取脚本
            string path;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "文本文件|*.txt|Windows脚本宿主文件|*.bat|所有文件|*.*";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;

                StreamReader sRead = new StreamReader(path);
                uiRichTextBox1.Text = sRead.ReadToEnd();
                sRead.Close();
            }
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //保存脚本
            string path;

            SaveFileDialog openFileDialog = new SaveFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "Windows脚本宿主文件|*.bat";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;

                StreamWriter sWrite = new StreamWriter(path);
                sWrite.Write(textBox1.Text);
                sWrite.Flush();
                sWrite.Close();
            }
        }

        private void 载入服务包ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //载入服务包

            string path;

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "垃圾服务包文件|*.gst";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;


            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;

                StreamReader sRead = new StreamReader(path);
                string servc = sRead.ReadToEnd();

                string[] tsp = servc.Split(';');
                List<string> a_servc = new List<string>(tsp); //包含的服务
            
                uiRichTextBox1.Text = "";

                int ins = 0;
                foreach (var item in a_servc)
                {
                    if (item == "") { }
                    else if (ins != 0)
                    {
                        uiRichTextBox1.Text += $"net stop {item.Substring(2)}\n";
                    }
                    else
                    {
                        uiRichTextBox1.Text += $"net stop {item}\n";
                    }

                    ins++;
                }

                ins = 0;

                InputWarning iw = new InputWarning(a_servc);
                iw.Show();
            }
        }

        private void 导出为包ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string[] res = uiRichTextBox1.Text.Split('\n');

            List<string> oup = new List<string>();

            foreach (var item in res)
            {
                try
                {
                    oup.Add(item.Substring(9));
                }
                catch
                {

                }
            }

            //保存脚本
            string path;

            SaveFileDialog openFileDialog = new SaveFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "垃圾服务包文件|*.gst";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;

                StreamWriter sWrite = new StreamWriter(path);

                foreach (var item in oup)
                {
                    sWrite.WriteLine(item
                        + ";");
                }
                sWrite.Flush();
                sWrite.Close();
            }
        }

        private void 启动服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (uiRichTextBox1.Text != "")
            {
                uiRichTextBox1.Text += "start 服务名 ";
            }
            else
            {
                uiRichTextBox1.Text += "net start 服务名 ";
            }
        }

        private void 停止服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (uiRichTextBox1.Text != "")
            {
                uiRichTextBox1.Text += "stop 服务名 ";
            }
            else
            {
                uiRichTextBox1.Text += "net stop 服务名 ";
            }
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            string url = "https://4ptcifn7j9.258jz.cn/api/regist.html";
            System.Diagnostics.Process.Start(url);
            ChromiumWebBrowser webview = new ChromiumWebBrowser(url);
            webview.Dock = DockStyle.Fill;
            tabPage7.Controls.Add(webview);
            uiTabControlMenu1.SelectedIndex = 5;
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            Login lg = new Login();
            lg.Show();
        }

        public static bool StopService(string serviceName, int timeoutMilliseconds)
        {
            bool ss = true;

            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

            }
            catch
            {
                MessageBox.Show("执行完成。");
            }
            return ss;
        }

        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            lb_serviceStopped.Items.Clear();

            List<string> stp = new List<string>();
            foreach (var item in uiListBox1.Items)
            {
                stp.Add(item.ToString());
            }

            if (stp.Count == 0)
            {
                MessageBox.Show("无服务！","请先扫描",MessageBoxButtons.OK,MessageBoxIcon.Error);

                return;
            }

            //开始♂停止服务

            string strInput = textBox1.Text;
            Process p = new Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = "cmd.exe";
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardInput = true;
            //输出信息
            p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            //启动程序
            p.Start();

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(strInput + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取输出信息
            string strOuput = p.StandardOutput.ReadToEnd();
            //等待程序执行完退出进程
            p.WaitForExit();
            p.Close();

            foreach (var item in stp)
            {
                bool status = StopService(item, 10000);

                if (status)
                {
                    lb_serviceStopped.Items.Add(item);
                }
            }
        }

        private void tabPage6_Click(object sender, EventArgs e)
        {

        }
    }
}
